#ifndef SQLITE3_UTILS_H
#define SQLITE3_UTILS_H

#ifndef _WIN32
#include <sqlite3sym.h>
#else
#include <sqlite3.h>
#endif

#include <stdbool.h>
#include <stdint.h>
#include "commtraff.h"
#include "common_list.h"

#ifdef __cplusplus
extern "C" {
#endif

#define DATABASE_NAME "/data/collectd/commtraff.db3"

// CommTraffNode结构体
typedef struct CommTraffNode {
    ListNode node;
    CommTraff data;
} CommTraffNode;

typedef struct {
    sqlite3 *db;
    sqlite3_stmt *stmt;
    uint32_t state;
} DbContext;

typedef enum {
    TABLE_SESSION_TRAFF,
    TABLE_TRANSPORT_TRAFF,
    TABLE_RPC_TRAFF,
    TABLE_WPA_TRAFF,
    TABLE_LINK_TRAFF,
    TABLE_HISYSEVENT_TRAFF,
    TABLE_NAME_ID_MAX,
} TableNameID;

typedef enum {
    CLOSE_TRANS_COMMIT = 0,
    CLOSE_TRANS_ROLLBACK
} CloseTransactionType;

typedef struct {
    DbContext *ctx;
    int64_t startTime;  // 查询开始时间
    int64_t endTime;    // 查询结束时间
    TraffType traffType; // 流量类型
    int64_t startRecordIndex; // 查询起始记录索引
} QueryParam;

/* read supports multithreading, and write only supports single thread {@link LOOP_TYPE_DEFAULT}. */
int32_t OpenDatabase(DbContext **ctx);
int32_t CloseDatabase(DbContext *ctx);

int32_t CreateTable(DbContext *ctx, TableNameID id);
int32_t DeleteTable(DbContext *ctx, TableNameID id);
int32_t CheckTableExist(DbContext *ctx, TableNameID id, bool *isExist);


int32_t InsertSessionTraffBatch(DbContext *ctx, ListNode *list);
int32_t InsertTransportTraffBatch(DbContext *ctx, ListNode *list);
int32_t InsertRpcTraffBatch(DbContext *ctx, ListNode *list);
int32_t InsertWpaTraffBatch(DbContext *ctx, ListNode *list);
int32_t InsertLinkTraffBatch(DbContext *ctx, ListNode *list);
int32_t InsertHisyseventTraffBatch(DbContext *ctx, ListNode *list);

// 新增基于时间范围的查询和删除函数
int32_t QueryTraffByTimeRange(QueryParam *queryParam, CommTraffResult *result);
int32_t DeleteOlderThan(DbContext *ctx, TableNameID id, int64_t beforeTime);

#ifdef __cplusplus
}
#endif
#endif